package org.darkforest.common.services.impl;

import org.darkforest.common.services.HealthPackageService;
import org.darkforest.dao.mapper.HealthPackageMapper;
import org.darkforest.model.HealthPackage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class HealthPackageServiceImpl implements HealthPackageService {

    @Autowired
    private HealthPackageMapper healthPackageMapper;

    @Override
    @Transactional
    public int deleteHealthPackage(String[] ids) {
        int delCount = 0;

        for (String id : ids) {
            // 先判断该数据是否已被删除
            HealthPackage healthPackage = healthPackageMapper.selectByPrimaryKey(Integer.parseInt(id));
            // 已被删除时，作为删除成功的数据来统计，因此删除件数+1
            if (healthPackage == null) {
                delCount = delCount + 1;
            } else {
                // 删除发生异常时，抛出 RuntimeException,事物自动回滚
                int j = healthPackageMapper.deleteByPrimaryKey(Integer.parseInt(id));
                delCount = delCount + j;
            }
        }

        if (delCount != ids.length) {
            // 删除失败时，事物回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return 0;
        }

        return 1;
    }
}
